<?php

namespace app\admin\controller;
use app\common\controller\Adminbase;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;

import('Curl', EXTEND_PATH);
import('Interfaces', EXTEND_PATH);
/**
 * 后台邮件控制器
 */
//class Email extends AdminBase {
 class Email extends controller{

    /**
     * 邮件页面
     * @return
     */
    public function Mail(){
        $this->assign('verify_type', config('verify_type'));
        return $this->fetch('Mail');
    }
    /**
     * 邮件历史记录 页面
     * @return
     */
    public function Mail_1(){
        $this->assign('verify_type', config('verify_type'));
        return $this->fetch('Mail_1');
    }
     /**
      * 邮件历史记录 页面
      * @return
      */
     public function mail_2(){
//         $this->assign('verify_type', config('verify_type'));
         return $this->fetch('Mail_2');
     }
    /**
     * 新建邮件
     * @return
     */
    public function new_email(){
        $establish_result = [];//创建时间 结果值
        $Login_result = [];//最后登录时间 结果值
        $all_result = [];//群发 结果值
        $recharge_result = [];//充值区间 结果值

        $recharge_min = input("param.recharge_min");//充值区间 最小
        $recharge_max = input("param.recharge_max");//充值区间 最大

        $establish_time = input("param.establish_time");//创建时间

        $Login_time = input("param.Login_time");//最后登录时间

        $sender = Session::get('username');;//发送人

        $recipient_type = input("param.recipient_type");//接收人

        $title = input("param.title");//标题

        $content = input("param.content");//内容（100字内）

        $send_time = date("Y-m-d H:i:s",time());//发送时间

        $UID_text = input("param.UID_text");

        $club_text = input("param.club_text");

        $assets_1 = input("param.assets_1");
        $assets_2 = input("param.assets_2");
        $assets_3 = input("param.assets_3");

        $assets_1_num = input("param.assets_1_num");
        $assets_2_num = input("param.assets_2_num");
        $assets_3_num = input("param.assets_3_num");

        $goods_assets_1 = "";
        $goods_assets_2 = "";
        $goods_assets_3 = "";

        if($assets_1 != ""){
            $assets_1_status = Db::name('assets')->where("id",$assets_1)->find();
            if($assets_1_status['status'] == 1){
                $break_up =explode(',',$assets_1_num);
                $goods_assets_1 = $break_up[0].'_'.$assets_1.','.$break_up[1].';';
            }else{
                $goods_assets_1 = $assets_1.','.$assets_1_num.';';
            }

        }
        if ($assets_2 != ""){
            $assets_2_status = Db::name('assets')->where("id",$assets_2)->find();
            if($assets_2_status['status'] == 1){
                $break_up =explode(',',$assets_2_num);
                $goods_assets_2 = $break_up[0].'_'.$assets_2.','.$break_up[1].';';
            }else {
                $goods_assets_2 = $assets_2 . ',' . $assets_2_num . ';';
            }
        }
        if ($assets_3 != ""){
            $assets_3_status = Db::name('assets')->where("id",$assets_3)->find();
            if($assets_3_status['status'] == 1){
                $break_up =explode(',',$assets_3_num);
                $goods_assets_3 = $break_up[0].'_'.$assets_3.','.$break_up[1].';';
            }else {
                $goods_assets_3 = $assets_3 . ',' . $assets_3_num . ';';
            }
        }
        $System = model('SystemModel');
        $g = $System->trimall($goods_assets_1.$goods_assets_2.$goods_assets_3);//去空格
        
        $goods  = rtrim($g, ';');

        //调用接口取 充值区间内的玩家id
        if($recharge_min !="" && $recharge_max !=""){

            $System = model('SystemModel');
            $recharge_result = $System->recharge($recharge_min,$recharge_max);
        }

        //调用接口取 创建时间内的玩家id
        if($establish_time !=""){

            $establish_start = substr($establish_time,0,19);
            $establish_end = substr($establish_time,22);
            $Interfaces = new \Interfaces();
            $establish_result = $Interfaces->establish_time(APP_ID,$establish_start,$establish_end);
        }
        //调用接口取 最后登录时间内的玩家id
        if($Login_time !=""){

            $Login_start = substr($Login_time,0,19);
            $Login_end = substr($Login_time,22);
            $Interfaces = new \Interfaces();
            $Login_result = $Interfaces->Login_time(APP_ID,$Login_start,$Login_end);
        }
        //群发 0
        if($recipient_type == 0){

            $Interfaces = new \Interfaces();
            $all_result = $Interfaces->all(APP_ID);

            $assets_1_status = Db::name('assets')->where("id",$assets_1)->find();
            if($assets_1_status['status'] == 1){
                echo "<script>alert('VIP卡不能群发');window.location.href='Mail'</script>";
            }
            $assets_2_status = Db::name('assets')->where("id",$assets_2)->find();
            if($assets_2_status['status'] == 1){
                echo "<script>alert('VIP卡不能群发');window.location.href='Mail'</script>";
            }
            $assets_3_status = Db::name('assets')->where("id",$assets_3)->find();
            if($assets_3_status['status'] == 1){
                echo "<script>alert('VIP卡不能群发');window.location.href='Mail'</script>";
            }
        }
        //UID 1
        if($recipient_type == 1 ){
            if(!empty($UID_text)){
                $all_result = explode(',', $UID_text);
            }else{
                $UID = request()->file('UID');
                if($UID){
                    $info = $UID->move(ROOT_PATH . 'public' . DS . 'uploads');
                }
                $file = file_get_contents($info->getPathName());//读取文件
                $all_result = explode(',', $file );//字符串分割成数组
            }
        }
        //俱乐部 2
        if($recipient_type == 2){
            if(!empty($club_text)){
                $System = model('SystemModel');
                $all_result = $System->club_user($club_text);
            }else{
                $club = request()->file('club');
                if($club){
                    $info = $club->move(ROOT_PATH . 'public' . DS . 'uploads');
                    $file = file_get_contents($info->getPathName());//读取文件
                    $System = model('SystemModel');
                    $all_result = $System->club_user($file);

                }


            }
        }

        if($recharge_min !="" && $recharge_max !="" && $establish_time !="" && $Login_time ==""){
            $recipient_arr = array_intersect($all_result,$establish_result,$recharge_result);//不选最后登录时间 [充值 创建 登录（空)]
        }
        if($recharge_min !="" && $recharge_max !="" && $establish_time =="" && $Login_time !=""){
            $recipient_arr = array_intersect($all_result,$Login_result,$recharge_result);//不选创建时间 [充值 创建（空） 登录]
        }
        if($recharge_min =="" && $recharge_max =="" && $establish_time !="" && $Login_time !=""){
            $recipient_arr = array_intersect($all_result,$Login_result,$establish_result);//不选充值区间 [充值（空） 创建 登录]
        }
        if($recharge_min !="" && $recharge_max !="" && $establish_time =="" && $Login_time ==""){
            $recipient_arr = array_intersect($all_result,$recharge_result);//只选充值区间 [充值 创建（空） 登录（空）]
        }
        if($recharge_min =="" && $recharge_max =="" && $establish_time !="" && $Login_time ==""){
            $recipient_arr = array_intersect($all_result,$establish_result);//只选创建时间 [充值（空） 创建 登录（空）]
        }
        if($recharge_min =="" && $recharge_max =="" && $establish_time =="" && $Login_time !=""){
            $recipient_arr = array_intersect($all_result,$Login_result);//只选最后登录时间 [充值（空） 创建（空） 登录]
        }
        if($recharge_min =="" && $recharge_max =="" && $establish_time =="" && $Login_time ==""){
            $recipient_arr = $all_result;//只选择收件人 [充值（空） 创建（空） 登录（空）]
        }
        if($recharge_min !="" && $recharge_max !="" && $establish_time !="" && $Login_time !=""){
            $recipient_arr = array_intersect($all_result,$establish_result,$Login_result,$recharge_result);//取数组交集 [充值 创建 登录]
        }
        // $recipient = implode(',',$recipient_arr);
        if(count($recipient_arr) == 0){
//            $this->error("信息填写错误,未找到数据");
            echo "<script>alert('信息填写错误,未找到数据');window.location.href='Mail'</script>";
        }else{

            $data = [
                'appid'=>APP_ID,//游戏服id
                'sender'=>0,//发收人
                'recipient'=>array_values($recipient_arr),//接收人
                'title'=>$title,
                'content'=>$content,
                'send_time'=>$send_time,
                'sender_type'=>2

            ];
            if(!empty($goods)){
                $System = model('SystemModel');
                $goods_result = $System->format($goods);
                $data['goods'] = $goods_result;
            }else{
                $data['goods'] = "";
            }
            $data = json_encode($data);
            $url =HTTP."api/email_add.php";
            $curl = new \Curl();
            $result = $curl->vpost($url,$data);
            $json = json_decode($result);
            if(!empty($json)){
                if($json->code == 0){
                    $url = AUDITING;
                    $refuse = [
                        'appid'=>APP_ID,
                        'type'=>1026,
                        'content'=>[
                        ],
                        'sender'=>0,
                        'reciver'=>array_values($recipient_arr),

                    ];
                    $refuse_json = json_encode($refuse);
                    $curl = new \Curl();
                    $message_result = $curl->vpost($url,$refuse_json);
                    $recipient = array_values($recipient_arr);
                    foreach ($recipient as $k=>$v){
                        $data_email = [
                            'sender'=>Session::get("username"),
                            'title'=>$title,
                            'content'=>$content,
                            'send_time'=>$send_time,
                            'type'=>1,
                            'operator'=>Session::get("username"),
                            'recipient'=>$v,
                        ];
                        if(!empty($goods)){
                            $System = model('SystemModel');
                            $goods_result = $System->format($goods);
                            $data_email['goods'] = $goods_result;
                        }else{
                            $data_email['goods'] = "";
                        }
                        Db::name("email")->insert($data_email);
                    }

                    echo "<script>alert('添加成功');window.location.href='Mail'</script>";
                }else{
                    echo "<script>alert('添加失败');window.location.href='Mail'</script>";
                }
            }else{
                echo "<script>alert('服务器错误');window.location.href='Mail'</script>";
            }

        }

    }
    /**
     * 获取邮件参数列表
     * @return
     */
    public function email_list_search(){
        $starTime = input("param.start_time");//开始时间
        $endTime = input("param.end_time");//结束时间
    	$uid = input("param.uid");//uid
        if($starTime =="" && $endTime =="" && $uid ==""){
            $starTime = date('Y-m-d', strtotime('-7 days'))." "."00:00:00";
            $endTime = date('Y-m-d', time())." "."23:59:59";
        }
    	if($starTime =="" && $endTime =="" && $uid !=""){
    	$starTime = "";
    	$endTime ="";
    	}
        $data = [
            'appid'=>APP_ID,
            'startDate'=>$starTime,
            'endDate'=>$endTime,
        	'sender_type'=>2,
        	'uid'=>$uid
        ];
    // print_r( $data);
        $data = json_encode($data);
//        $url =HTTP."api/email_list_search.php";
        $url =HTTP."api/email_sys_search.php";
        $curl = new \Curl();
        $result = $curl->vpost($url,$data);
        $obj = json_decode($result);
        foreach ($obj->data as $key => $value) {
            
            $b = (array)json_decode($value->goods);
            $str = "";
            foreach ($b as $k=> $v) {
               $str.= $k.','.$v.';';
            }
            $str=rtrim($str, ";");
            $value->goods= $str;
        }
        return json($obj->data); 
    }
    /**
     * 邮件撤销
     * @return
     */
    public function email_undo(){
        $id = input("param.id");
        $data = [
            'appid'=>APP_ID,
            'id'=>$id,
        ];
        $data = json_encode($data);
        $url =HTTP."api/email_undo.php";
        $curl = new \Curl();
        $result = $curl->vpost($url,$data);

        return $result;
    }
    /**
     * 系统撤销邮件
     * @return
     */
    public function email_sys_undo(){
        $send_no = input("param.send_no");
        $title = input("param.title");
        $goods = input("param.goods");
        $content = input("param.content");
        $recipient = input("param.recipient");
        $sender = input("param.sender");
        $operator = Session::get("username");
        $data = [
            'appid'=>APP_ID,
            'send_no'=>$send_no,
        ];
        $data = json_encode($data);
        $url =HTTP."api/email_sys_undo.php";
        $curl = new \Curl();
        $result = $curl->vpost($url,$data);
        $data_email = [
            'title'=>$title,
            'goods'=>$goods,
            'content'=>$content,
            'recipient'=>$recipient,
            'sender'=>$sender,
            'operator'=>$operator,
            'type'=>2
        ];
        Db::name("email")->insert($data_email);
        return $result;
    }
	/**
      * 物品列表
      * @return
      */
     public function assets(){
        $assets = Db::name('assets')->select();
        return json($assets);
     }

     /**
      * 物品列表
      * @return
      */
     public function email_list(){
            $where = [];
            $start_time =  input("param.start_time ");
            $end_time=  input("param.end_time");
            $uid=  input("param.uid");
            $type=  input("param.type");
            if($start_time !="" && $end_time !=""){
                $where['send_time'] =array(array('Egt',$start_time),array('Elt',$end_time), 'and');
            }
            if($uid !=""){
                $where['recipient'] = $uid;
            }
             if($type !=""){
                 $where['type'] = $type;
             }
         $assets = Db::name('email')
             ->where($where)
             ->select();

         return json($assets);
     }
}